<?php

/* ----------------------------------------------
  Caloris: Module Extensions

  $Id$
  $Author$

  Seznam s extenzí s možností uploadu nové extenze
  ---------------------------------------------- */

require_once("../../../index.php");
Caloris\ACL::authenticate();

define('_MODULE_ACTIVE', 'modulemanager');

$urlExtensions = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/extensions.xml';

if ($_REQUEST["function_name"] == 'extension_upload') {
    if (Caloris\ACL::authorize("extensions") == 1) {
        $folders = _CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $_FILES['the_file']['name'];

        if ($_FILES['the_file']['name'] == "none") {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE. "/modulemanager/index.php?msg=" . urlencode("Chyba při uploadu"));
            exit();
        }

        // Popisek
        copy($_FILES['the_file']['tmp_name'], $folders);
        chmod($folders, 0777);

        $filein = Caloris\IO::get(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $_FILES['the_file']['name']);
        $startin = strpos($filein, "/*");
        $endin = strpos($filein, "*/");
        $descriptor = explode(":", substr($filein, ($startin + 2), (($endin - $startin)) - 2));

        // Find the comment section of the extension
        $extensionPositionStart .= strpos($filein, '<extension');
        $extensionPositionEnd .= strpos($filein, '</extension>') + 12;
        $extensionXmlString = html_entity_decode(substr($filein, $extensionPositionStart, ($extensionPositionEnd - $extensionPositionStart)), 0, 'UTF-8');
        $extensionXml = simplexml_load_string($extensionXmlString);

        if (count($extensionXml)) {
            $extensionName = $extensionXml[0]["id"];
            $extensionAuthor = $extensionXml[0]->author;
            $extensionDescription = $extensionXml[0]->description;
            $extensionModule = $extensionXml[0]->modules->name;
        } else {
            $extensionName = substr($_FILES['the_file']['name'], 0, -4);
            $extensionAuthor = '';
            $extensionDescription = $descriptor[1];
            $extensionModule = '';
        }

        $extension = simplexml_load_file($urlExtensions);
        $extensionExists = $extension->xpath('//extension[@id="' . $extensionName . '"]');

        if (count($extensionExists) > 0) {
            $extensionExists[0]->author = $extensionAuthor;
            $extensionExists[0]->description = $extensionDescription;

            unset($extensionExists[0]->modules);

            if (count($extensionModule) > 0) {

                for ($c = 0; $c < count($extensionModule); $c++) {
                    $extensionExists[0]->modules->name[] = $extensionModule[$c];
                }
            }

            $extension->asXML($urlExtensions);
        } else {
            $xt = $extension->AddChild("extension");
            $xt["id"] = $extensionName;
            $xt->author = $extensionAuthor;
            $xt->description = $extensionDescription;

            if (count($extensionModule) > 0) {
                $md = $xt->AddChild("modules");

                for ($c = 0; $c < count($extensionModule); $c++) {
                    $md->name[] = $extensionModule[$c];
                }
            }

            $extension->asXML($urlExtensions);
        }

        //--------------------------------------------------

        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE. "/modulemanager/extensions.php?msg=" . urlencode("Extenze uložena"));
        exit();
    } else {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE. "/modulemanager/extensions.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }
} elseif ($_REQUEST["function_name"] == 'extension_delete') {

    if (Caloris\ACL::authorize("extensions") == 1) {
        $fileName = _CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $_POST["extension"] . '.php';


        // Smazání stránky z pages.xml
        $doc = new DOMDOcument;
        $doc->load($urlExtensions);
        $xpath = new DOMXpath($doc);
        $query = '//extension[@id="' . $_POST["extension"] . '"]';

        foreach ($xpath->query($query) as $node) {
            $node->parentNode->removeChild($node);
        }

        $doc->save($urlExtensions);

        if (file_exists($fileName)) {
            unlink($fileName);
        }
    } else {
        if ($_POST["j"] != 1) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE. "/modulemanager/index.php?msg=" . urlencode("Nemáte oprávnění"));
            exit();
        } else {
            echo "{\"msg\": \"Nemáte oprávnění\"}";
            exit();
        }
    }
}


$content = '
<span style="color: red;" id="msg">[cal:predefs(msg) /]</span>

<h1>Extenze</h1>

<p style="padding-bottom: 20px; max-width: 1080px;">Přehled uživatelských extenzí. Extenze jsou funkce rozšiřující možnosti stránek. Zapisují se obvykle takto &#91;cal:jménoextenze /&#93;, pokud mají argumenty. 
Pak například takto &#91;cal:jménoextenze(první;druhý) /&#93;. Systémové extenze by neměly být mazány.</p>
';
if (Caloris\ACL::authorize("extensions") == 1) {
    $formUploadExtension = new Nette\Forms\Form;
    $formUploadExtension->setAction(_CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/modulemanager/extensions.php');
    $formUploadExtension->getElementPrototype()->class = 'cform';
    $formUploadExtension->addHidden('function_name', 'extension_upload');
    $formUploadExtension->addUpload('the_file');
    $formUploadExtension->addSubmit('name', 'Přidat');

    $content .= $formUploadExtension . PHP_EOL;
}

$content.= '<h2>Seznam extenzí</h2>';

// Registrace nových extenzí, kde chybí zápis v XML souboru

$extensionDirectory = scandir(_CALSET_PATHS_BASE . '/cal-components/extensions');

for ($a = 0; $a < count($extensionDirectory); $a++) {
    $extensionNameNoExt = substr($extensionDirectory[$a], 0, -4);
    $extensionFileName = $extensionDirectory[$a];

    if ($extensionDirectory[$a] == '.' or $extensionDirectory[$a] == '..') {
        
    } else {
        // Search for existence of extensions in extensions directory. Deletes records in XML file for non-existing extensions, adds XML descriptions for extension files
        $xmlExtensionsCheck = new Caloris\XML();
        $xmlExtensionsCheck->source($urlExtensions);
        $xmlExtensionsCheck->filter('//extension[@id="' . $extensionNameNoExt . '"]');


        if (count($xmlExtensionsCheck->output) == 0) {

            $filein = Caloris\IO::get(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $extensionFileName);
            $startin = strpos($filein, "/*");
            $endin = strpos($filein, "*/");
            $descriptor = explode(":", substr($filein, ($startin + 2), (($endin - $startin)) - 2));

            // Find the comment section of the extension
            $extensionPositionStart .= strpos($filein, '<extension');
            $extensionPositionEnd .= strpos($filein, '</extension>') + 12;
            $extensionXmlString = html_entity_decode(substr($filein, $extensionPositionStart, ($extensionPositionEnd - $extensionPositionStart)), 0, 'UTF-8');
            $extensionXml = simplexml_load_string($extensionXmlString);

            if (count($extensionXml)) {
                $extensionName = $extensionXml[0]["id"];
                $extensionAuthor = $extensionXml[0]->author;
                $extensionDescription = $extensionXml[0]->description;
                $extensionModule = $extensionXml[0]->modules->name;
            } else {
                $extensionName = $extensionFileName;
                $extensionAuthor = '';
                $extensionDescription = $descriptor[1];
                $extensionModule = '';
            }

            $extension = simplexml_load_file($urlExtensions);
            $extensionExists = $extension->xpath('//extension[@id="' . $extensionNameNoExt . '"]');

            $xt = $extension->AddChild("extension");
            $xt["id"] = $extensionName;
            $xt->author = $extensionAuthor;
            $xt->description = $extensionDescription;

            if (count($extensionModule) > 0) {
                $md = $xt->AddChild("modules");

                for ($c = 0; $c < count($extensionModule); $c++) {
                    $md->name[] = $extensionModule[$c];
                }
            }

            $extension->asXML($urlExtensions);
        }
    }

    unset($extensionNameNoExt);
}

// Listování extenzí
$xmlExtensions = new Caloris\XML();
$xmlExtensions->source($urlExtensions);
$xmlExtensions->filter('//extension');

//echo print_r($xmlExtensions->output);

if (count($xmlExtensions->output) > 0) {
    $content .= '
<table class="table table-striped">
    <tr>
        <th style="width: 20px;">&nbsp;</th>
        <th style="width: 20px;">&nbsp;</th>
        <th>Název extenze</th>
        <th>Popis</th>
        <th style="width: 20px;">Modul</th>
    </tr>
';

    for ($x = 0; $x < count($xmlExtensions->output); $x++) {
        if (!file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $xmlExtensions->output[$x]["id"] . '.php')) {
            // Smazání stránky z pages.xml
            $doc = new DOMDOcument;
            $doc->load($urlExtensions);
            $xpath = new DOMXpath($doc);
            $query = '//extension[@id="' . $xmlExtensions->output[$x]["id"] . '"]';

            foreach ($xpath->query($query) as $node) {
                $node->parentNode->removeChild($node);
            }

            $doc->save($urlExtensions);
        } else {
            if (Caloris\ACL::authorize("extensions") == 1) {
                if ($xmlExtensions->output[$x]->name["system"] == 1) {
                    $linkDelete = '';
                } else {
                    $linkDelete = '
<form id="formshw_' . $xmlExtensions->output[$x]["id"] . '" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/modulemanager/extensions.php" name="trbl_' . $xmlExtensions->output[$x]["id"] . '" method="post" onsubmit="return false;">
<input type="hidden" name="function_name" value="extension_delete"  />
<input type="hidden" name="extension" value="' . $xmlExtensions->output[$x]["id"] . '"  />
<input type="image" src="' . _CALSET_PATHS_URI . _CALSET_DIRS_TEMPLATE . '/caloris-admin/images/cancel.gif" id="formx_' . $xmlExtensions->output[$x]["id"] . '" />
</form>';
                }
            }

            $xmlModulesList = '';

            for ($l = 0; $l < count($xmlExtensions->output[$x]->modules->name); $l++) {
                $xmlModulesList .= $xmlExtensions->output[$x]->modules->name[$l] . ',';
            }

            $content .= '
    <tr id="trbl_' . $xmlExtensions->output[$x]["id"] . '" >
        <td>' . $linkDelete . '</td>
        <td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/modulemanager/edit.php?file=' . $xmlExtensions->output[$x]["id"] . '.php">
            <img src="' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN_IMAGE . '/images/edit.gif" alt="Upravit" width="16" height="16" /></a>
        </td>
        <td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/modulemanager/edit.php?file=' . $xmlExtensions->output[$x]["id"] . '.php">' . $xmlExtensions->output[$x]["id"] . '</a></td>
        <td>' . $xmlExtensions->output[$x]->description . '</td>
        <td>' . substr($xmlModulesList, 0, -1) . '&nbsp;</td>
        </td>
    </tr>';
        }
    }

    $content .= '
</table>' . PHP_EOL;
} else {
    $content .= '<p>Žádné extenze nenalezeny</p>';
}

$data["title"] = 'Extenze';

$tmpl = new Caloris\Template;
$tmpl->input($content);
$tmpl->renderHead($data);
echo $tmpl->renderBody('caloris-admin');